// HttpServer.hpp
#pragma once
#include <iostream>
#include <pthread.h>
#include "TcpSocket.hpp"

static const int defaultport = 8080;

class HttpServer;

class ThreadData
{
public:
    ThreadData(int fd, HttpServer *ts) :sockfd(fd), httpsvr(ts)
    {}
public:
    int sockfd;
    HttpServer *httpsvr;
};

class HttpServer
{
public:
    HttpServer(uint16_t port = defaultport)
        : _port(port)
    {
    }
    bool Start()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = _listensock.Accept(&clientip, &clientport);
            if (sockfd < 0)
                continue;
            lg(Info, "get a new connect, sockfd: %d", sockfd);
            
            pthread_t tid;
            ThreadData *td = new ThreadData(sockfd, this);
            pthread_create(&tid, nullptr, ThreadRun, td);
        }
    }
    static void *ThreadRun(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->httpsvr->HandlerHttp(td->sockfd);
        delete td;
        return nullptr;
    }
    void HandlerHttp(int sockfd)
    {
        char buffer[10240];
        ssize_t n = recv(sockfd, buffer, sizeof(buffer) - 1, 0);  // 无法保证读到一个完整报文
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer;  // 收到什么就打印出什么

            // 返回响应
            std::string text = "hello world";  // 正文
            std::string response_line = "HTTP/1.0 200 OK\r\n";  // 状态行
            std::string response_header = "Content-Length: ";  // 响应报头
            response_header += std::to_string(text.size());
            response_header += "\r\n";
            std::string blank_line = "\r\n";  // 空行

            std::string response = response_line;  // 整个报文
            response += response_header;
            response += blank_line;
            response += text;

            send(sockfd, response.c_str(), response.size(), 0);
        }
        close(sockfd);
    }
    ~HttpServer()
    {
    }

private:
    TcpSocket _listensock;
    uint16_t _port;
};
